#!/bin/bash

API_BASE="http://localhost:3002/api/v1"

echo "🔐 Testing Plugin Signature System"
echo ""

# 1. 登录获取管理员token
echo "1. Login as admin"
LOGIN_RESPONSE=$(curl -s -X POST "$API_BASE/auth/login" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "testdev@example.com",
    "password": "password123"
  }')

# 提取token
TOKEN=$(echo "$LOGIN_RESPONSE" | grep -o '"accessToken":"[^"]*"' | cut -d'"' -f4)

if [ -z "$TOKEN" ]; then
  echo "❌ Admin login failed"
  echo "Response: $LOGIN_RESPONSE"
  exit 1
fi

echo "✅ Admin login successful"
echo ""

# 2. 生成签名证书
echo "2. Generate signing certificate"
CERT_RESPONSE=$(curl -s -X POST "$API_BASE/signature/certificates/generate" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "issuer": "Bai-hu Plugin Cloud Platform"
  }')

echo "Certificate Response: $CERT_RESPONSE"
echo ""

# 提取keyId
KEY_ID=$(echo "$CERT_RESPONSE" | grep -o '"keyId":"[^"]*"' | cut -d'"' -f4)

if [ -z "$KEY_ID" ]; then
  echo "❌ Certificate generation failed"
  exit 1
fi

echo "✅ Certificate generated with keyId: $KEY_ID"
echo ""

# 3. 获取证书信息
echo "3. Get certificate information"
CERT_INFO_RESPONSE=$(curl -s -X GET "$API_BASE/signature/certificates/$KEY_ID")
echo "Certificate Info: $CERT_INFO_RESPONSE"
echo ""

# 4. 获取所有活跃证书
echo "4. Get all active certificates"
ALL_CERTS_RESPONSE=$(curl -s -X GET "$API_BASE/signature/certificates" \
  -H "Authorization: Bearer $TOKEN")
echo "All Certificates: $ALL_CERTS_RESPONSE"
echo ""

# 5. 获取一个插件版本ID进行签名测试
echo "5. Get plugin version for signing test"
PLUGINS_RESPONSE=$(curl -s -X GET "$API_BASE/admin/plugins/pending" \
  -H "Authorization: Bearer $TOKEN")
echo "Pending Plugins: $PLUGINS_RESPONSE"

# 提取第一个插件的版本ID (需要先获取插件版本)
# 这里我们先跳过实际签名，因为需要有实际的插件版本

echo ""
echo "6. Test signature statistics"
STATS_RESPONSE=$(curl -s -X GET "$API_BASE/signature/stats" \
  -H "Authorization: Bearer $TOKEN")
echo "Signature Stats: $STATS_RESPONSE"
echo ""

echo "🎉 Signature system testing completed!"
echo "Note: To test actual plugin signing, you need to upload a plugin version first."
